package org.mbds.android.sismapp.activity;

import org.mbds.android.sismapp.R;
import org.mbds.android.sismapp.SismappMenu;
import org.mbds.android.sismapp.SismappStaticCommons;
import org.mbds.android.sismapp.R.layout;
import org.mbds.android.sismapp.R.menu;
import org.mbds.android.sismapp.SismappMessage;

import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ViewSwitcher;

public class AlertActivity extends Activity {
	private Ringtone r;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_alert);
		Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
		r = RingtoneManager.getRingtone(getApplicationContext(), notification);
		r.play();		
		// Check if quake has already been confirmed
		if (SismappStaticCommons.getSeismicAlertLevel()
				==SismappStaticCommons.SEISMIC_ALERT_LEVEL_USER_CONFIRMED)
			emergencyView();
	}

	public void confirmQuake(View view) {
		r.stop();
		try {
			SismappMessage.sendSismappMessage(SismappMessage.MESSAGE_SEISMIC_ALERT_CONFIRMED);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Display emergency view
		emergencyView();
	}
	
	public void noQuake(View view) {
		// Return previous activity...
		finish();
	}
	
	public void emergencyView() {
		ViewSwitcher switcher = (ViewSwitcher) findViewById(R.id.switcher_alert);
		switcher.showNext();
	}
	
	@Override
	public void finish() {
		// reset alert level
		r.stop();
		SismappStaticCommons.setSeismicAlertLevel(SismappStaticCommons.SEISMIC_ALERT_LEVEL_NONE);
		super.finish();
	}
	
	/***********************/
	/* Create options menu */
	/***********************/
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		SismappMenu.onCreateOptionsMenu(this, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/************************/
	/* Prepare options menu */
	/************************/
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		SismappMenu.onPrepareOptionsMenu(this, menu);
		return super.onPrepareOptionsMenu(menu);
	}

	/*******************************/
	/* Manage menu item selection */
	/*******************************/
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		SismappMenu.onOptionsItemSelected(this, item);
		return super.onOptionsItemSelected(item);
	}

}
